package com.newhero.doc2pdf.convert.controller;

import com.newhero.doc2pdf.convert.model.JsonResult;
import com.newhero.doc2pdf.convert.util.JacobConvertUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping(value = "/", produces = "application/json; charset=utf-8")
public class ConvertController {

  @GetMapping("/testPing.newhero")
  public JsonResult testPing() {
    JsonResult jsonResult = new JsonResult();
    jsonResult.setCode(JsonResult.CODE_SUCCES);
    jsonResult.setMsg("测试请求成功！");
    return jsonResult;
  }

  @PostMapping("/docConvertToPdf.newhero")
  public JsonResult docConvertToPdf(String docFilePath) {
    JsonResult jsonResult = new JsonResult();
    if (StringUtils.isEmpty(docFilePath)) {
      jsonResult.setCode(JsonResult.CODE_FAIL);
      jsonResult.setMsg("没有必要参数：docFilePath=" + docFilePath);
    } else {
      File file = new File(docFilePath);
      if (file.exists()) {
        try {
          JacobConvertUtil.doc2pdf(docFilePath);
          jsonResult.setCode(JsonResult.CODE_SUCCES);
          jsonResult.setMsg("转换成功。");
        } catch (Exception e) {
          e.printStackTrace();
          jsonResult.setCode(JsonResult.CODE_FAIL);
          jsonResult.setMsg("转换时出现异常。");
          jsonResult.setObj(new String(e.getMessage()));
        }
      } else {
        jsonResult.setCode(JsonResult.CODE_FAIL);
        jsonResult.setMsg("服务器未找到该文件。" + docFilePath);
      }
    }
    return jsonResult;
  }
}
